using System;
using System.Collections.Generic;
using System.Linq;
using ODT.Common.Core;
using ODT.Common.ExtensionMethods;
using ODT.Common.WPF.Core;
using ODT.Intellisense.Core;

namespace IntellisenseControl
{
	public sealed class IntellisenseProcessor : IIntellisenseProcessor
	{
		private const string DatabaseName = "ppmac";

		private static readonly object DatabaseLock = new object();

		private readonly IDatabaseService databaseService;

		//private readonly IDeviceConnectionController deviceConnectionController;

		private readonly IInputProcessingService inputProcessingService;

		private readonly IIntellisenseDatabaseService intellisenseDatabaseService;

		private readonly IWordProcessingService wordProcessingService;

		private string database;

        private string connectionString;

        public IntellisenseProcessor(IDatabaseService databaseService, /*IDeviceConnectionController deviceConnectionController, */IInputProcessingService inputProcessingService, IIntellisenseDatabaseService intellisenseDatabaseService, IWordProcessingService wordProcessingService)
        {
            this.databaseService = databaseService;
            this.inputProcessingService = inputProcessingService;
            this.intellisenseDatabaseService = intellisenseDatabaseService;
            this.wordProcessingService = wordProcessingService;
            //this.deviceConnectionController = deviceConnectionController;
            //this.deviceConnectionController.ConnectedToDevice += OnConnected;
            database = "ppmac";
            connectionString = this.databaseService.GetConnectionString(database);
        }

        public bool CanSkipFillSuggestions(string newInput, string oldInput)
		{
			if (string.IsNullOrWhiteSpace(newInput))
			{
				return false;
			}
			if (string.IsNullOrWhiteSpace(oldInput))
			{
				return false;
			}
			string prefixOfLastCompound = inputProcessingService.GetPrefixOfLastCompound(newInput);
			string prefixOfLastCompound2 = inputProcessingService.GetPrefixOfLastCompound(oldInput);
			if (!prefixOfLastCompound.Equals(prefixOfLastCompound2))
			{
				return false;
			}
			return true;
		}

		public void FillSuggestions(string input, IList<string> suggestions)
		{
			suggestions.ThrowArgumentNullException("suggestions");
			try
			{
				if (!databaseService.IsDatabaseRunning())
				{
					return;
				}
			}
			catch { }

			input = input ?? string.Empty;
			string prefixOfLastCompound = inputProcessingService.GetPrefixOfLastCompound(input);
			string[] words = inputProcessingService.GetWords(prefixOfLastCompound);
			if (words.Length == 0)
			{
				intellisenseDatabaseService.GetLevel0List(connectionString, suggestions);
				return;
			}
			string alias = intellisenseDatabaseService.GetAlias(words[0], connectionString);
			if (!string.IsNullOrEmpty(alias) && alias != "null")
			{
				words[0] = alias;
			}
			string[] array = new string[words.Length];
			for (int i = 0; i < words.Length; i++)
			{
				array[i] = wordProcessingService.RemoveNumberBetweenBrackets(words[i]);
			}
			intellisenseDatabaseService.GetAllOtherLevelList(array, connectionString, suggestions);
		}

		public string PickASuggestion(string input, IReadOnlyList<string> suggestions)
		{
			suggestions.ThrowArgumentNullException("suggestions");
			input = input ?? string.Empty;
			string lastWord = inputProcessingService.GetLastWord(input);
			return FindClosestMatchedString(lastWord, suggestions);
		}

		public int GetReplacementStartIndex(string input)
		{
			input = input ?? string.Empty;
			return inputProcessingService.GetBeforeLastWord(input).Length;
		}

		public string CombineWithSuggestion(string input, string suggestion)
		{
			input = input ?? string.Empty;
			return inputProcessingService.GetBeforeLastWord(input) + suggestion;
		}

		public string GetHelpText(string suggestion)
		{
			suggestion = suggestion ?? string.Empty;
			return intellisenseDatabaseService.GetHelpText(suggestion, connectionString);
		}

		private string FindClosestMatchedString(string text, IReadOnlyList<string> list)
		{
			string result = list.FirstOrDefault() ?? string.Empty;
			for (int num = text.Length; num > 0; num--)
			{
				string substring = text.Substring(0, num).ToLower();
				string text2 = list.FirstOrDefault((string s) => s.ToLower().StartsWith(substring));
				if (text2 != null)
				{
					return text2;
				}
			}
			return result;
		}

		//private void OnConnected(object sender, EventArgs e)
		public void OnConnected(string IP_Address)
		{
            lock (DatabaseLock)
            {
                string text = IP_Address.Replace('.', '_');
                if (text.IsNoDevice())
                {
                    text = "ppmac";
                }
                if (!text.ToLower().Contains("ppmac"))
                {
                    text = "ppmac" + text;
                }
                text = text.Replace('.', '_');
                database = text;
                connectionString = databaseService.GetConnectionString(database);
            }
        }
	}
}
